﻿using CodeCarvings.Piczard;
using LuShanTea.Admin.Web.App_Start;
using LuShanTea.Admin.Web.Models;
using LuShanTea.Common;
using LuShanTea.DTO;
using LuShanTea.IService;

using LuShanTea.Web.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LuShanTea.Admin.Web.Controllers
{
    public class GoodController : Controller
    {
        public IGoodService goodService { get; set; }   // 商品
        public IPackService packService { get; set; }   // 包装类型
        public IProvinceService provinceSer { get; set; }   // 省份
        public ICityService citySer { get; set; }   // 市
        public ICategoryService categorySer { get; set; }   // 商品类型
        public IGoodImsSrcService goodImgSer { get; set; }
        // 获取第一页的商品
        [CheckPermission("Good.List")]
        [HttpGet]
        public ActionResult List()
        {
            ViewBag.totalCount = goodService.GetAll().Count();
            GoodDTO[] goods = goodService.GetPageData(1);
            return View(goods);
        }

        // 分页获取商品
        [CheckPermission("Good.List")]
        [HttpPost]
        public ActionResult List(int index = 1)
        {
            ViewBag.totalCount = goodService.GetAll().Count();
            GoodDTO[] goods = goodService.GetPageData(index);
            return Json(goods);
        }

        // 添加商品
        [CheckPermission("Good.Add")]
        [HttpGet]
        public ActionResult AddNew()
        {

            GoodAddNewGetModel model = new GoodAddNewGetModel();
            var packs = packService.GetAll();   // 获取所有的包装类型
            var provinces = provinceSer.GetAll();   // 获取所有的省
            long firstProvinceId = provinces.First().Id; // 获取第一个省下的id
            var citys = citySer.GetByProvId(firstProvinceId); // 获取指定省下的市
            var categorys = categorySer.GetAll();
            model.Categorys = categorys;
            model.Citys = citys;
            model.Provinces = provinces;
            model.Packs = packs;
            return View(model);
        }
        [CheckPermission("Good.Add")]
        [HttpPost]
        public ActionResult AddNew(GoodAddNewPostModel model)
        {
            GoodDTO dto = new GoodDTO();
            dto.CateGoriesId = model.CateGoriesId;
            dto.CityId = model.CityId;
            dto.Descible = model.Descible;
            dto.Name = model.Name;
            dto.PackIds = model.PackIds;
            dto.PrePrice = model.PrePrice;
            dto.Price = model.PrePrice;
            dto.Selled = model.Selled;
            dto.TotalCount = model.TotalCount;
            dto.Weight = model.Weight;
            long id = goodService.AddNew(dto);

            // 如果添加商品成功，则把商品也添加到elastic search中去
            dto.Id = id;
            try
            {
                LuShanTeaElasticSearch.Insert(dto);
            }
            catch
            {
                Console.WriteLine("插入失败");

            }
           
            if (id > 0)
            {
                return Json(new AjaxResult { Status = "ok" });
            }
            return Json(new AjaxResult { Status = "error" });
        }


        // 更新商品类型
        [CheckPermission("Good.Edit")]
        [HttpGet]
        public ActionResult Edit(long goodId)
        {
            GoodEditGetModel model = new GoodEditGetModel();
            var packs = packService.GetAll();   // 获取所有的包装类型
            var provinces = provinceSer.GetAll();   // 获取所有的省
            var categorys = categorySer.GetAll();
            var good = goodService.GetByGoodId(goodId);
            long provinceId = citySer.GetProvinceIdByCityId(good.CityId); // 获取该市所在省
            var citys = citySer.GetByProvId(provinceId); // 获取指定省下的市
            model.ProvinceId = provinceId;
            model.Good = good;
            model.Categorys = categorys;
            model.Citys = citys;
            model.Provinces = provinces;
            model.Packs = packs;
            return View(model);
        }
        [CheckPermission("Good.Edit")]
        [HttpPost]
        public ActionResult Edit(GoodEditPostModel model)
        {
            GoodDTO dto = new GoodDTO();
            dto.CateGoriesId = model.CateGoriesId;
            dto.CityId = model.CityId;
            dto.Descible = model.Descible;
            dto.Id = model.Id;
            dto.Name = model.Name;
            dto.PackIds = model.PackIds;
            dto.PrePrice = model.PrePrice;
            dto.Selled = model.Selled;
            dto.Price = model.Price;
            dto.TotalCount = model.TotalCount;
            dto.Weight = model.Weight;
            goodService.Updata(dto);
            return Json(new AjaxResult { Status = "ok" });
        }

        // 图片上传
        [CheckPermission("Image.List")]
        [HttpGet]
        public ActionResult UploadPic(long goodId)
        {
            ViewBag.goodId = goodId;
            return View();
        }
        [CheckPermission("Image.List")]
        [HttpPost]
        public ActionResult UploadPic(long goodId, HttpPostedFileBase file)
        {
            // 获取上传的文件，计算出他们的md5值，用于作为他们的文件名
            string md5 = CommonHelper.CalcMD5(file.InputStream);
            string extendPath = Path.GetExtension(file.FileName);   // 获取上传文件的后缀名
            string path = "upload/goodImgs/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + md5 + extendPath; // 定义原始图片文件存储目录

            string thumbPath = path + "?imageView2/2/w/200/h/200/interlace/1/q/100";

            #region 原始代码
            //string thumbPath = "upload/goodImgs" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + md5 + "_thumb" + extendPath;// 定义缩略图文件存储目录

            //string fullPath = HttpContext.Server.MapPath("~" + path);   // 获取原始图片文件全路径
            //string thumbFullPath = HttpContext.Server.MapPath("~" + thumbPath);// 获取缩略图片文件全路径

            //判断该目录下的这个文件是否存在，存在不创建，不存在则新创建一个
            //new FileInfo(fullPath).Directory.Create();

            ////缩略图
            //ImageProcessingJob jobThumb = new ImageProcessingJob();
            //jobThumb.Filters.Add(new FixedResizeConstraint(200, 200));//缩略图尺寸200*200
            //jobThumb.(file.InputStream);//将六中缩略后保存到thumbfullpath中 

            //file.SaveAs(fullPath);
            #endregion

            //指针归零
            file.InputStream.Position = 0;
            UploadFile uploadFile = new UploadFile();

            AjaxResult ajaxResult = uploadFile.UploadImg(path, file.InputStream);

            GoodImgSrcDTO dto = new GoodImgSrcDTO();
            dto.CreateDateTime = DateTime.Now;
            dto.DescImgSrc = "";
            dto.GoodId = goodId;
            dto.ImgSrc = path;
            dto.ThumImgSrc = thumbPath;
            long id = goodImgSer.AddNew(dto);
            if (id <= 0)
            {
                return Json(new AjaxResult { Status = "error" });
            }
            return Json(new AjaxResult { Status = "ok" });
        }
        [CheckPermission("Image.List")]
        // 商品图片展示
        public ActionResult PicList(long goodId)
        {
            var pics = goodImgSer.GetImgsByGoodId(goodId);
            if (pics.Count() <= 0)// 说明该商品还没上传图片,则让他跳转到图片上传上去
            {
                return Redirect("/Good/UploadPIc?goodId=" + goodId);
            }
            return View(pics);
        }

        // 获取指定省下所有的市
        public ActionResult GetCityByProvinceId(long provinceId)
        {
            var model = citySer.GetByProvId(provinceId);
            return Json(new AjaxResult { Status = "ok", Data = model });
        }
        [CheckPermission("Good.Delete")]
        // 软删除
        public ActionResult Delete(long goodId)
        {
            goodService.MakeDelete(goodId);
            return Json(new AjaxResult { Status = "ok" });
        }

        // 批量删除
        [CheckPermission("Good.Delete")]
        public ActionResult BatchDel(long[] goodIds)
        {
            foreach (var goodId in goodIds)
            {
                goodService.MakeDelete(goodId);
            }
            return Json(new AjaxResult { Status = "ok" });
        }
        // 修改商品
    }
}